package com.mustafaiev.tair.mweather.connectivity;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.mustafaiev.tair.mweather.exception.MWeatherApiException;

/**
 * Class for internet connection management Creation date: 29 Aug 2011 22:34:44
 * 
 * @author Tair Mustafaiev
 * 
 */
public class ConnectionManager {

	/**
	 * GisMeteo Informer page without city id
	 */
	public static final String INFORMER_PAGE = "http://informer.gismeteo.ru/xml/";

	public static final String INFORMER_PAGE_POSTFIX = "_1.xml";

	/**
	 * {@link StatusLine} HTTP status code when no server error has occurred.
	 */
	private static final int HTTP_STATUS_OK = 200;

	/**
	 * Pull the raw text content of the given URL. This call blocks until the
	 * operation has completed, and is synchronized because it uses a shared
	 * buffer {@link #sBuffer}.
	 * 
	 * @param url
	 *            The exact URL to request.
	 * @return The raw content returned by the server.
	 * @throws MWeatherApiException
	 * @throws ApiException
	 *             If any connection or server error occurs.
	 */
	public static synchronized InputStream getUrlContent(String cityId)
			throws MWeatherApiException {

		// initializes url
		String url = ConnectionManager.INFORMER_PAGE + cityId
				+ ConnectionManager.INFORMER_PAGE_POSTFIX;

		// Create client and set our specific user-agent string
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);

		Log.i("ConnectionManager, method getUrlContent() request",
				request.toString());

		try {
			HttpResponse response = client.execute(request);

			Log.i("ConnectionManager, method getUrlContent() response",
					response.toString());
			// Check if server response is valid
			StatusLine status = response.getStatusLine();
			if (status.getStatusCode() != ConnectionManager.HTTP_STATUS_OK) {
				throw new MWeatherApiException("Invalid response from server: "
						+ status.toString());
			}

			// Pull content stream from response
			HttpEntity entity = response.getEntity();
			InputStream inputStream = entity.getContent();

			// Return result from buffered stream
			return inputStream;
		} catch (IOException e) {
			throw new MWeatherApiException("Problem communicating with API", e);
		}
	}

}
